import React, { useState, useEffect } from 'react';
import { Button, Text, Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, Spinner, Select, Label, Input, Popover, PopoverContent, PopoverTrigger } from 'packages/ui-shared/src/atoms';
import { getTeachers, addTeacher, updateTeacher, deleteTeacher } from '../mock/teacherData';
import { mockClasses } from '../mock/classData'; 

// 定义教师接口，扩展原始接口添加新字段
interface Teacher {
  id: number;
  name: string;
  gender: string;
  age?: number;
  title?: string;
  department: string; // 就业学院
  phone: string;
  joinDate: string;
  courses?: string;
  successRate?: number;
  managedClasses: number[]; // 注意：这里保持number[]类型，在使用时转换
  idNumber: string; // 身份证号
  teachingProgress: string; // 教学进度
  status: 'employed' | 'resigned'; // 状态：在职/离职
}

// 可选就业学院列表
const availableDepartments = [
  '人工智能', '新媒体', '数据分析', '计算机科学', '软件工程', '信息安全'
];


export default function TeacherManagementPage() {
  const [teachers, setTeachers] = useState<Teacher[]>([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [selectedTeacherId, setSelectedTeacherId] = useState<number | null>(null);
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  
  // 筛选状态
  const [filters, setFilters] = useState({
    name: '',
    department: '',
    status: 'all'
  });
  
  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    gender: '男',
    department: '',
    phone: '',
    joinDate: '',
    managedClasses: [] as number[],
    idNumber: '',
    teachingProgress: '专业1',
    status: 'employed' as 'employed' | 'resigned'
  });
  
  // 表单验证错误
  const [errors, setErrors] = useState({
    name: '',
    phone: '',
    idNumber: '',
    department: '',
    joinDate: ''
  });

  useEffect(() => {
    loadTeachers();
  }, []);

  // 加载教师列表
  const loadTeachers = async () => {
    setLoading(true);
    try {
      const teachersData = await getTeachers();
      // 处理数据，添加新字段
      const enrichedTeachers = teachersData.map((teacher: any) => ({
        ...teacher,
        idNumber: teacher.idNumber || generateIdNumber(teacher.id), // 生成身份证号
        teachingProgress: teacher.teachingProgress || `专业${Math.floor(Math.random() * 5) + 1}`, // 生成教学进度
        status: teacher.status === 'active' ? 'employed' : teacher.status === 'inactive' ? 'resigned' : (Math.random() > 0.2 ? 'employed' : 'resigned') // 映射状态
      }));
      setTeachers(enrichedTeachers);
      setCurrentPage(1); // 重置到第一页
    } catch (error) {
      console.error('加载教师列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 生成模拟身份证号
  const generateIdNumber = (id: number): string => {
    const baseId = '110101';
    const birthYear = 1980 + Math.floor((id * 7) % 30);
    const birthMonth = String(Math.floor((id * 3) % 12) + 1).padStart(2, '0');
    const birthDay = String(Math.floor((id * 5) % 28) + 1).padStart(2, '0');
    const sequence = String(id).padStart(4, '0');
    return `${baseId}${birthYear}${birthMonth}${birthDay}${sequence}`;
  };

  // 处理操作按钮点击
  const handleAction = (teacherId: number, actionType: 'view' | 'edit' | 'delete') => {
    setSelectedTeacherId(teacherId);
    
    if (actionType === 'edit') {
      // 查找要编辑的教师
      const teacherToEdit = teachers.find(teacher => teacher.id === teacherId);
      if (teacherToEdit) {
        setFormData(teacherToEdit);
        setIsEditOpen(true);
      }
    } else if (actionType === 'delete') {
      setIsDeleteOpen(true);
    } else if (actionType === 'view') {
      // 查看详情功能（可以扩展）
      alert(`查看教师ID: ${teacherId} 的详情`);
    }
  };
  
  // 添加辅助函数，根据班级ID获取班级名称
  const getClassName = (classIds: number[]): string => {
    return classIds
      .map(id => {
        // 转换ID类型并查找对应的班级名称
        const className = mockClasses.find(c => c.id === id.toString());
        return className ? className.className : `未知班级(${id})`;
      })
      .join(', ');
  };
  
  // 验证手机号
  const validatePhone = (phone: string): boolean => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };
  
  // 验证身份证号
  const validateIdNumber = (idNumber: string): boolean => {
    const idRegex = /(^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}$)/;
    return idRegex.test(idNumber);
  };
  
  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // 清除对应字段的错误信息
    setErrors(prev => ({ ...prev, [name]: '' }));
  };
  
  // 处理班级选择变化（改为单选）
  const handleClassSelection = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedValue = e.target.value;
    // 转换为数组格式以保持数据结构一致性
    const managedClasses = selectedValue ? [parseInt(selectedValue)] : [];
    setFormData(prev => ({ ...prev, managedClasses }));
  };
  
  // 处理性别选择
  const handleGenderChange = (gender: string) => {
    setFormData(prev => ({ ...prev, gender }));
  };
  
  // 处理状态选择
  const handleStatusChange = (status: 'employed' | 'resigned') => {
    setFormData(prev => ({ ...prev, status }));
  };
  
  // 验证表单
  const validateForm = (): boolean => {
    let isValid = true;
    const newErrors = {
      name: '',
      phone: '',
      idNumber: '',
      department: '',
      joinDate: ''
    };
    
    if (!formData.name) {
      newErrors.name = '请输入教师姓名';
      isValid = false;
    }
    
    if (!formData.phone) {
      newErrors.phone = '请输入联系方式';
      isValid = false;
    } else if (!validatePhone(formData.phone)) {
      newErrors.phone = '请输入有效的手机号码';
      isValid = false;
    }
    
    if (!formData.idNumber) {
      newErrors.idNumber = '请输入身份证号';
      isValid = false;
    } else if (!validateIdNumber(formData.idNumber)) {
      newErrors.idNumber = '请输入有效的身份证号';
      isValid = false;
    }
    
    if (!formData.department) {
      newErrors.department = '请选择就业学院';
      isValid = false;
    }
    
    if (!formData.joinDate) {
      newErrors.joinDate = '请选择入职日期';
      isValid = false;
    }
    
    setErrors(newErrors);
    return isValid;
  };
  
  // 提交表单（添加）
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    try {
      setLoading(true);
      // 调用添加教师的API
      await addTeacher({
        ...formData,
        age: 30 + Math.floor(Math.random() * 20), // 随机年龄
        title: '讲师', // 默认职称
        courses: '计算机基础', // 默认课程
        successRate: 85 + Math.floor(Math.random() * 15) // 随机成才率
      });
      
      // 重新加载教师列表
      await loadTeachers();
      
      // 重置表单
      resetForm();
      
      // 关闭模态框
      setIsAddOpen(false);
      
      alert('教师添加成功！');
    } catch (error) {
      console.error('添加教师失败:', error);
      alert('添加教师失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 提交编辑表单
  const handleEditSubmit = async () => {
    if (!validateForm() || !selectedTeacherId) {
      return;
    }
    
    try {
      setLoading(true);
      // 调用更新教师的API
      await updateTeacher(selectedTeacherId, formData);
      
      // 重新加载教师列表
      await loadTeachers();
      
      // 重置表单
      resetForm();
      
      // 关闭模态框
      setIsEditOpen(false);
      
      alert('教师信息更新成功！');
    } catch (error) {
      console.error('更新教师失败:', error);
      alert('更新教师失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除教师
  const handleDeleteTeacher = async () => {
    if (!selectedTeacherId) {
      return;
    }
    
    try {
      setLoading(true);
      // 调用删除教师的API
      await deleteTeacher(selectedTeacherId);
      
      // 重新加载教师列表
      await loadTeachers();
      
      // 关闭确认对话框
      setIsDeleteOpen(false);
      
      alert('教师删除成功！');
    } catch (error) {
      console.error('删除教师失败:', error);
      alert('删除教师失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: '',
      gender: '男',
      department: '',
      phone: '',
      joinDate: '',
      managedClasses: [],
      idNumber: '',
      teachingProgress: '专业1',
      status: 'employed'
    });
    setErrors({});
  };

  // 筛选教师
  const filteredTeachers = teachers.filter(teacher => {
    if (filters.name && !teacher.name.includes(filters.name)) {
      return false;
    }
    if (filters.department && teacher.department !== filters.department) {
      return false;
    }
    if (filters.status !== 'all' && teacher.status !== filters.status) {
      return false;
    }
    return true;
  });

  // 分页计算
  const totalPages = Math.ceil(filteredTeachers.length / pageSize);
  const startIndex = (currentPage - 1) * pageSize;
  const paginatedTeachers = filteredTeachers.slice(startIndex, startIndex + pageSize);

  // 处理筛选变化
  const handleFilterChange = (filterType: string, value: string) => {
    setFilters(prev => ({ ...prev, [filterType]: value }));
    setCurrentPage(1); // 重置到第一页
  };

  return (
    <div className="p-6 bg-white">
      {/* 页面标题和添加按钮 */}
      <div className="mb-6 flex justify-between items-center">
        <Text className="text-2xl font-bold text-gray-900">教师管理</Text>
        <Button onClick={() => setIsAddOpen(true)}>
          添加教师
        </Button>
      </div>

      {/* 筛选条件 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div className="space-y-2">
          <Label htmlFor="name-filter">教师姓名</Label>
          <Input
            id="name-filter"
            value={filters.name}
            onChange={(e) => handleFilterChange('name', e.target.value)}
            placeholder="搜索教师姓名"
          />
        </div>
        
        <div className="space-y-2">
          <Label htmlFor="department-filter">就业学院</Label>
          <Select
            id="department-filter"
            value={filters.department}
            onValueChange={(value) => handleFilterChange('department', value)}
          >
            <option value="">所有学院</option>
            {availableDepartments.map((dept, index) => (
              <option key={index} value={dept}>{dept}</option>
            ))}
          </Select>
        </div>
        
        <div className="space-y-2">
          <Label htmlFor="status-filter">状态</Label>
          <Select
            id="status-filter"
            value={filters.status}
            onValueChange={(value) => handleFilterChange('status', value)}
          >
            <option value="all">所有状态</option>
            <option value="employed">在职</option>
            <option value="resigned">离职</option>
          </Select>
        </div>
      </div>

      {/* 添加教师模态框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>添加新教师</DialogTitle>
            <DialogDescription>
              请填写教师信息，带 * 的为必填项
            </DialogDescription>
          </DialogHeader>
          
          <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4 py-4">
            {/* 教师姓名 - 改为输入框 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">教师姓名 *</label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                placeholder="请输入教师姓名"
                className={`w-full p-2 border rounded ${errors.name ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.name && <span className="text-red-500 text-sm">{errors.name}</span>}
            </div>
            
            {/* 性别 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">性别</label>
              <div className="flex space-x-4">
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="gender"
                    value="男"
                    checked={formData.gender === '男'}
                    onChange={() => handleGenderChange('男')}
                    className="mr-1"
                  />
                  男
                </label>
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="gender"
                    value="女"
                    checked={formData.gender === '女'}
                    onChange={() => handleGenderChange('女')}
                    className="mr-1"
                  />
                  女
                </label>
              </div>
            </div>
            
            {/* 联系方式 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">联系方式 *</label>
              <input
                type="text"
                name="phone"
                value={formData.phone}
                onChange={handleInputChange}
                placeholder="请输入手机号码"
                className={`w-full p-2 border rounded ${errors.phone ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.phone && <span className="text-red-500 text-sm">{errors.phone}</span>}
            </div>
            
            {/* 身份证号 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">身份证号 *</label>
              <input
                type="text"
                name="idNumber"
                value={formData.idNumber}
                onChange={handleInputChange}
                placeholder="请输入身份证号"
                className={`w-full p-2 border rounded ${errors.idNumber ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.idNumber && <span className="text-red-500 text-sm">{errors.idNumber}</span>}
            </div>
            
            {/* 所带班级 - 改为单选下拉框 */}
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">所带班级</label>
              <select
                value={formData.managedClasses.length > 0 ? formData.managedClasses[0] : ''}
                onChange={handleClassSelection}
                className="w-full p-2 border border-gray-300 rounded"
              >
                <option value="">请选择所带班级</option>
                {mockClasses.map(cls => (
                  <option key={cls.id} value={parseInt(cls.id)}>{cls.className} - {cls.description}</option>
                ))}
              </select>
            </div>
            
            {/* 教学进度 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">教学进度</label>
              <select
                name="teachingProgress"
                value={formData.teachingProgress}
                onChange={handleInputChange}
                className="w-full p-2 border border-gray-300 rounded"
              >
                <option value="专业1">专业1</option>
                <option value="专业2">专业2</option>
                <option value="专业3">专业3</option>
                <option value="专业4">专业4</option>
                <option value="专业5">专业5</option>
              </select>
            </div>
            
            {/* 入职日期 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">入职日期 *</label>
              <input
                type="date"
                name="joinDate"
                value={formData.joinDate}
                onChange={handleInputChange}
                className={`w-full p-2 border rounded ${errors.joinDate ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.joinDate && <span className="text-red-500 text-sm">{errors.joinDate}</span>}
            </div>
            
            {/* 就业学院 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">就业学院 *</label>
              <select
                name="department"
                value={formData.department}
                onChange={handleInputChange}
                className={`w-full p-2 border rounded ${errors.department ? 'border-red-500' : 'border-gray-300'}`}
              >
                <option value="">请选择就业学院</option>
                {availableDepartments.map((dept, index) => (
                  <option key={index} value={dept}>{dept}</option>
                ))}
              </select>
              {errors.department && <span className="text-red-500 text-sm">{errors.department}</span>}
            </div>
            
            {/* 状态 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
              <div className="flex space-x-4">
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="status"
                    value="employed"
                    checked={formData.status === 'employed'}
                    onChange={() => handleStatusChange('employed')}
                    className="mr-1"
                  />
                  在职
                </label>
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="status"
                    value="resigned"
                    checked={formData.status === 'resigned'}
                    onChange={() => handleStatusChange('resigned')}
                    className="mr-1"
                  />
                  离职
                </label>
              </div>
            </div>
          </form>

          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => {
              resetForm();
              setIsAddOpen(false);
            }}>
              取消
            </Button>
            <Button type="submit" formMethod="dialog" onClick={handleSubmit} disabled={loading}>
              {loading ? '提交中...' : '提交'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑教师模态框 */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>编辑教师信息</DialogTitle>
            <DialogDescription>
              修改教师信息，带 * 的为必填项
            </DialogDescription>
          </DialogHeader>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-4">
            {/* 教师姓名 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">教师姓名 *</label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                placeholder="请输入教师姓名"
                className={`w-full p-2 border rounded ${errors.name ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.name && <span className="text-red-500 text-sm">{errors.name}</span>}
            </div>
            
            {/* 性别 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">性别</label>
              <div className="flex space-x-4">
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="gender"
                    value="男"
                    checked={formData.gender === '男'}
                    onChange={() => handleGenderChange('男')}
                    className="mr-1"
                  />
                  男
                </label>
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="gender"
                    value="女"
                    checked={formData.gender === '女'}
                    onChange={() => handleGenderChange('女')}
                    className="mr-1"
                  />
                  女
                </label>
              </div>
            </div>
            
            {/* 联系方式 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">联系方式 *</label>
              <input
                type="text"
                name="phone"
                value={formData.phone}
                onChange={handleInputChange}
                placeholder="请输入手机号码"
                className={`w-full p-2 border rounded ${errors.phone ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.phone && <span className="text-red-500 text-sm">{errors.phone}</span>}
            </div>
            
            {/* 身份证号 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">身份证号 *</label>
              <input
                type="text"
                name="idNumber"
                value={formData.idNumber}
                onChange={handleInputChange}
                placeholder="请输入身份证号"
                className={`w-full p-2 border rounded ${errors.idNumber ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.idNumber && <span className="text-red-500 text-sm">{errors.idNumber}</span>}
            </div>
            
            {/* 所带班级 */}
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">所带班级</label>
              <select
                value={formData.managedClasses.length > 0 ? formData.managedClasses[0] : ''}
                onChange={handleClassSelection}
                className="w-full p-2 border border-gray-300 rounded"
              >
                <option value="">请选择所带班级</option>
                {mockClasses.map(cls => (
                  <option key={cls.id} value={parseInt(cls.id)}>{cls.className} - {cls.description}</option>
                ))}
              </select>
            </div>
            
            {/* 教学进度 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">教学进度</label>
              <select
                name="teachingProgress"
                value={formData.teachingProgress}
                onChange={handleInputChange}
                className="w-full p-2 border border-gray-300 rounded"
              >
                <option value="专业1">专业1</option>
                <option value="专业2">专业2</option>
                <option value="专业3">专业3</option>
                <option value="专业4">专业4</option>
                <option value="专业5">专业5</option>
              </select>
            </div>
            
            {/* 入职日期 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">入职日期 *</label>
              <input
                type="date"
                name="joinDate"
                value={formData.joinDate}
                onChange={handleInputChange}
                className={`w-full p-2 border rounded ${errors.joinDate ? 'border-red-500' : 'border-gray-300'}`}
              />
              {errors.joinDate && <span className="text-red-500 text-sm">{errors.joinDate}</span>}
            </div>
            
            {/* 就业学院 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">就业学院 *</label>
              <select
                name="department"
                value={formData.department}
                onChange={handleInputChange}
                className={`w-full p-2 border rounded ${errors.department ? 'border-red-500' : 'border-gray-300'}`}
              >
                <option value="">请选择就业学院</option>
                {availableDepartments.map((dept, index) => (
                  <option key={index} value={dept}>{dept}</option>
                ))}
              </select>
              {errors.department && <span className="text-red-500 text-sm">{errors.department}</span>}
            </div>
            
            {/* 状态 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
              <div className="flex space-x-4">
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="status"
                    value="employed"
                    checked={formData.status === 'employed'}
                    onChange={() => handleStatusChange('employed')}
                    className="mr-1"
                  />
                  在职
                </label>
                <label className="inline-flex items-center">
                  <input
                    type="radio"
                    name="status"
                    value="resigned"
                    checked={formData.status === 'resigned'}
                    onChange={() => handleStatusChange('resigned')}
                    className="mr-1"
                  />
                  离职
                </label>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => {
              resetForm();
              setIsEditOpen(false);
            }}>
              取消
            </Button>
            <Button type="button" onClick={handleEditSubmit} disabled={loading}>
              {loading ? '更新中...' : '更新'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
          </DialogHeader>
          <p className="py-4">您确定要删除此教师信息吗？此操作无法撤销。</p>
          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => setIsDeleteOpen(false)}>
              取消
            </Button>
            <Button type="button" variant="destructive" onClick={handleDeleteTeacher} disabled={loading}>
              {loading ? '删除中...' : '删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 教师列表表格 */}
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>教师姓名</TableHead>
              <TableHead>性别</TableHead>
              <TableHead>身份证号</TableHead>
              <TableHead>所带班级</TableHead>
              <TableHead>联系方式</TableHead>
              <TableHead>教学进度</TableHead>
              <TableHead>入职日期</TableHead>
              <TableHead>就业学院</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={10} className="text-center py-8">
                  <Spinner className="mx-auto" />
                </TableCell>
              </TableRow>
            ) : paginatedTeachers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={10} className="text-center py-8">
                  暂无教师数据
                </TableCell>
              </TableRow>
            ) : (
              paginatedTeachers.map((teacher) => (
                <TableRow key={teacher.id}>
                  <TableCell>{teacher.name}</TableCell>
                  <TableCell>{teacher.gender}</TableCell>
                  <TableCell>{teacher.idNumber}</TableCell>
                  <TableCell>{getClassName(teacher.managedClasses)}</TableCell>
                  <TableCell>{teacher.phone}</TableCell>
                  <TableCell>{teacher.teachingProgress}</TableCell>
                  <TableCell>{teacher.joinDate}</TableCell>
                  <TableCell>{teacher.department}</TableCell>
                  <TableCell>
                    <span className={`px-2 py-1 rounded text-sm ${teacher.status === 'employed' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                      {teacher.status === 'employed' ? '在职' : '离职'}
                    </span>
                  </TableCell>
                  <TableCell>
                    <div className="flex space-x-2">
                      <Button size="sm" className="h-7" onClick={() => handleAction(teacher.id, 'view')}>查看</Button>
                      <Button size="sm" className="h-7" onClick={() => handleAction(teacher.id, 'edit')}>编辑</Button>
                      <Button size="sm" className="h-7" onClick={() => handleAction(teacher.id, 'delete')}>删除</Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页控件 */}
      {totalPages > 1 && (
        <div className="flex justify-between items-center mt-6">
          <div>
            <span className="text-sm text-gray-600">
              显示 {startIndex + 1} - {Math.min(startIndex + pageSize, filteredTeachers.length)} 条，共 {filteredTeachers.length} 条
            </span>
          </div>
          <div className="flex space-x-2">
            <Button 
              size="sm" 
              onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              上一页
            </Button>
            {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
              // 计算要显示的页码
              let pageToShow = i + 1;
              if (totalPages > 5) {
                if (currentPage > 3 && currentPage < totalPages - 2) {
                  pageToShow = currentPage - 2 + i;
                } else if (currentPage >= totalPages - 2) {
                  pageToShow = totalPages - 4 + i;
                }
              }
              
              return (
                <Button
                  key={pageToShow}
                  size="sm"
                  variant={currentPage === pageToShow ? "default" : "ghost"}
                  onClick={() => setCurrentPage(pageToShow)}
                >
                  {pageToShow}
                </Button>
              );
            })}
            <Button 
              size="sm" 
              onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
              disabled={currentPage === totalPages}
            >
              下一页
            </Button>
          </div>
          <div>
            <select 
              value={pageSize}
              onChange={(e) => setPageSize(Number(e.target.value))}
              className="p-1 border border-gray-300 rounded"
            >
              <option value="5">5条/页</option>
              <option value="10">10条/页</option>
              <option value="20">20条/页</option>
            </select>
          </div>
        </div>
      )}
    </div>
  );
}